package ua.at.tsvetkov.samizdat.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.Utils;
import ua.at.tsvetkov.samizdat.database.ContentProviderSamizdat;
import ua.at.tsvetkov.util.Log;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;

public class AsyncTaskTextDownload extends AsyncTask<Void, Integer, Void> {
	private Context	context;
	private URL			url;
	private String		bookPath;
	private Integer	bookId;

	public AsyncTaskTextDownload(Service context, String bookPath, Integer id) {
		this.context = context;
		this.bookPath = bookPath;
		this.bookId = id;
		try {
			this.url = new URL(Url.getBookDownloadUrl() + bookPath);
		} catch (MalformedURLException e) {
			Log.e("Illegal url");
		}
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected Void doInBackground(Void... params) {

		BufferedReader in = null;
		try {
			HttpURLConnection connection;
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(Const.TIMEOUT * 15 * 10);
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
			connection.setRequestProperty("User-Agent", "Android reader");
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Const.ENCODING), 12000);

			String currentString;
			StringBuffer result = new StringBuffer();

			while ((currentString = in.readLine()) != null) {
				result.append(removeHtmlTag(currentString));
			}

			File currentFile = new File(Utils.getHomeDirectoryPath(context), String.valueOf(bookId) + ".txt");

			saveToFile(currentFile, result.toString());

			Cursor resultCursor = context.getContentResolver().query(Uri.parse(ContentProviderSamizdat.BOOK_CONTENT_URI + "/"), new String[] { Const.BOOK_PATH },
					Const.OBJECT + "=" + "'" + bookPath + "'", null, null);
			resultCursor.moveToFirst();

			ContentValues bookUpdate = new ContentValues();
			bookUpdate.put(Const.BOOK_PATH, String.valueOf(bookId) + ".txt");
			context.getContentResolver().update(Uri.parse(ContentProviderSamizdat.BOOK_CONTENT_URI + "/"), bookUpdate, Const.OBJECT + "=" + "'" + bookPath + "'", null);

			connection.disconnect();
		} catch (Exception e) {
			if (e instanceof FileNotFoundException || e instanceof UnknownHostException) {
				Intent broadcastIntent = new Intent(Const.BROADCAST_MESSAGE).putExtra(Const.SERVER_IS_UNAVAILABLE, Const.SERVER_IS_UNAVAILABLE);
				context.sendBroadcast(broadcastIntent);
			}
			Log.e(e);
		}
		Log.v(Const.DOWNLOAD_TEXT_SUCCESS);
		return null;
	}

	private void saveToFile(File file, String text) throws FileNotFoundException {
		FileOutputStream fos = new FileOutputStream(file);
		try {
			fos.write(text.getBytes());
			fos.close();
		} catch (IOException e) {
			Log.e("Save to file failed!!");
		}
	}

	@Override
	protected void onProgressUpdate(Integer... progress) {

	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		((Service) context).stopSelf();
	}

	private static String removeHtmlTag(String src) {
		if (src == null)
			return null;
		return src.replaceAll("Ђ|ђ|&shy;", "")/* .replaceAll("<.*?>|Ђ|ђ|&shy;", "").replaceAll("&nbsp;", " ") */.replaceAll("&quot;", "\"")/* .replaceAll(" {2,}?", "\n") */.replaceAll("<dd>", "<br>");
	}

}
